import { useState, useEffect } from "react";
import useEventListener from "@hooks/useEventListener";

type UseMediaQueryReturn = boolean;

export default function useMediaQuery(mediaQuery: string): UseMediaQueryReturn {
  const [isMatch, setIsMatch] = useState<boolean>(false);
  const [mediaQueryList, setMediaQueryList] = useState<MediaQueryList | null>(
    null
  );

  useEffect(() => {
    const list = window.matchMedia(mediaQuery);
    setMediaQueryList(list);
    setIsMatch(list.matches);
  }, [mediaQuery]);

  useEventListener(
    "change",
    (e) => setIsMatch((e as MediaQueryListEvent).matches),
    mediaQueryList
  );

  return isMatch;
}
